package com.gxuwz.attend.web.servlet;

import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 基于页面控制器模式的登录验证
 * @author amu_1115@126.com
 * @version 1.0
 */
@WebServlet(name = "loginServlet",urlPatterns = {"/login"})
public class LoginServlet extends BaseHttpServlet {
    private  final static String  VIEW_MAIN="index.jsp";
    private  final static String  VIEW_LOGIN="login.jsp";
    //业务组件-
    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
         //从IoC容器获取实例化bean组件
         userService= AppContext.getBean(UserService.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1:接收参数
         String username =req.getParameter("username");
         String password =req.getParameter("password");
         String code =req.getParameter("code");//验证码，暂不启用
        //2:调用service组件
         try{
             //验证用户+密码的合法性
             boolean flag = userService.checkUser(username,password);
             if (flag){
                 super.doDispatch(req,resp,VIEW_MAIN);
             }else{
                 super.doDispatch(req,resp,VIEW_LOGIN);
             }
         }catch (Exception e){
             e.printStackTrace();
              super.doRedirect(req,resp,req.getContextPath()+ErrorPage_500);
         }
        //3:返回响应报文
    }
}
